package com.mia.craftstudio.minecraft;

import com.google.common.collect.HashBiMap;
import java.util.ArrayList;

public enum AnimationManager {
   INSTANCE;

   private ArrayList animationStates = new ArrayList();
   private HashBiMap animationsMap = HashBiMap.create();
   private final ArrayList EMPTY_LIST = new ArrayList();

   public void update(float timeDelta) {
      for(int i = this.animationStates.size() - 1; i >= 0; --i) {
         AnimationManager.TrackedObjectAnimationStates animState = (AnimationManager.TrackedObjectAnimationStates)this.animationStates.get(i);
         animState.update(timeDelta);
         if (animState.activeAnimations.isEmpty()) {
            this.animationStates.remove(i);
            this.animationsMap.inverse().remove(animState);
         }
      }

   }

   public static ArrayList getActiveAnimations(Object o) {
      AnimationManager.TrackedObjectAnimationStates animObj = (AnimationManager.TrackedObjectAnimationStates)INSTANCE.animationsMap.get(o);
      return animObj != null ? animObj.activeAnimations : INSTANCE.EMPTY_LIST;
   }

   public static boolean addAnimationState(Object o, AnimationState state) {
      AnimationManager.TrackedObjectAnimationStates animObj = (AnimationManager.TrackedObjectAnimationStates)INSTANCE.animationsMap.get(o);
      if (animObj == null) {
         animObj = new AnimationManager.TrackedObjectAnimationStates();
         INSTANCE.animationsMap.put(o, animObj);
         INSTANCE.animationStates.add(animObj);
         animObj.activeAnimations.add(state);
         return true;
      } else {
         return false;
      }
   }

   public static class TrackedObjectAnimationStates {
      public ArrayList activeAnimations = new ArrayList();

      public void update(float timeDelta) {
         for(int i = this.activeAnimations.size() - 1; i >= 0; --i) {
            AnimationState anim = (AnimationState)this.activeAnimations.get(i);
            System.out.println(System.currentTimeMillis());
            System.out.println(anim.frameTime);
            short duration = anim.animation.getAnimationDuration();
            if (anim.frameTime >= (float)duration) {
               if (anim.repeatCount > 0 && --anim.repeatCount == 0) {
                  this.activeAnimations.remove(i);
                  continue;
               }

               anim.frameTime -= (float)duration;
               anim.lastFullFrameRendered -= duration;
            }

            anim.frameTime += timeDelta;
         }

      }
   }
}
